import MediaGrid from "@/components/MediaGrid";
import { ThemedView } from "@/components/ThemedView";
import {
  SelectedMediaItem,
  useMediaSelection,
} from "@/contexts/MediaSelectionContext";
import { MaterialIcons } from "@expo/vector-icons";
import * as ImagePicker from "expo-image-picker";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useRef, useState } from "react";
import { Alert, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { useSafeAreaInsets } from 'react-native-safe-area-context';


type MediaType = "photo" | "video" | "all" | "camera";

interface MediaItem {
  id: string;
  uri: string;
  type: "photo" | "video" | "camera";
  duration?: number;
  creationTime: number;
  width?: number;
  height?: number;
}

interface RouteParams {
  mode?: "single" | "multiple";
  mediaType?: MediaType;
  maxCount?: number;
  redirectTo?: string;
  onSelectCallback?: string; // 用于传递选择结果的回调标识
}

/**
 * 图片/视频选择器组件
 * 支持单选/多选模式
 * 支持图片/视频类型过滤
 * 支持相机拍摄（单选模式下）
 */
export default function SelectImageScreen() {
  const insets = useSafeAreaInsets();
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const [filterType, setFilterType] = useState<MediaType>("all");

  const params = useLocalSearchParams();
  const router = useRouter();
  const { setSelectedMedia: setGlobalSelectedMedia } = useMediaSelection();
  const mediaGridRef = useRef<any>(null);

  const mode = (params.mode as RouteParams["mode"]) || "single";
  const maxCount = Number(params.maxCount) || (mode === "multiple" ? 9 : 1);

  /**
   * 单选模式处理
   */
  const handleSingleSelect = (item: MediaItem) => {
    if (item.type === "camera") {
      handleTakePhoto();
      return;
    }

    const selectedMediaItems = convertToSelectedMediaItem([item]);

    // 使用全局状态管理
    setGlobalSelectedMedia(selectedMediaItems);

    // 跳转到图片处理页面
    router.replace("/detail/image-process");
  };

  /**
   * 多选模式处理
   */
  const handleMultipleSelect = (items: MediaItem[]) => {
    const selectedMediaItems = convertToSelectedMediaItem(items);

    // 使用全局状态管理
    setGlobalSelectedMedia(selectedMediaItems);

    // 跳转到图片处理页面
    router.replace("/detail/image-process");
  };

  /**
   * 切换选中状态（仅用于多选模式）
   */
  const toggleSelection = (item: MediaItem) => {
    if (item.type === "camera") {
      return;
    }

    setSelectedItems((prev) => {
      if (prev.includes(item.id)) {
        return prev.filter((id) => id !== item.id);
      }

      if (prev.length >= maxCount) {
        Alert.alert("提示", `最多只能选择 ${maxCount} 个文件`);
        return prev;
      }

      return [...prev, item.id];
    });
  };

  /**
   * 将MediaItem转换为SelectedMediaItem，过滤掉camera类型
   */
  const convertToSelectedMediaItem = (
    mediaItems: MediaItem[]
  ): SelectedMediaItem[] => {
    return mediaItems
      .filter((item) => item.type === "photo" || item.type === "video")
      .map((item) => ({
        id: item.id,
        url: item.uri, // 将 url 改为 uri，与 SelectedMediaItem 类型保持一致
        type: item.type as "photo" | "video",
        duration: item.duration,
        creationTime: item.creationTime,
        width: (item as any).width,
        height: (item as any).height,
      }));
  };

  /**
   * 确认选择
   */
  const handleConfirm = () => {
    if (selectedItems.length === 0) {
      Alert.alert("提示", "请先选择图片");
      return;
    }

    const selectedMedia =
      mediaGridRef.current?.getMediaByIds(selectedItems) || [];
    handleMultipleSelect(selectedMedia);
  };

  /**
   * 使用相机拍照（无论单选多选都清空数据并设置为当前图片）
   */
  const handleTakePhoto = async () => {
    try {
      const { status } = await ImagePicker.requestCameraPermissionsAsync();
      if (status !== "granted") {
        Alert.alert("权限不足", "需要相机权限才能拍照");
        return;
      }

      const result = await ImagePicker.launchCameraAsync({
        mediaTypes: "images",
        allowsEditing: false,
        quality: 0.8,
      });

      if (!result.canceled && result.assets[0]) {
        const asset = result.assets[0];
        const newMedia: MediaItem = {
          id: `camera_${Date.now()}`,
          uri: asset.uri,
          type: "photo",
          creationTime: Date.now(),
        };

        // 清空之前的选择数据
        setSelectedItems([]);

        // 设置为当前图片（无论单选多选模式）
        const selectedMedia = [newMedia];
        const selectedMediaItems = convertToSelectedMediaItem(selectedMedia);

        // 使用全局状态管理
        setGlobalSelectedMedia(selectedMediaItems);

        // 跳转到图片处理页面
        router.replace("/detail/image-process");
      }
    } catch (error) {
      console.error("拍照错误:", error);
      Alert.alert("错误", "拍照失败，请重试");
    }
  };

  return (
    <ThemedView style={styles.container}>
      <Stack.Screen options={{ headerShown: false }} />
      {/* 自定义头部 */}
      <View style={[styles.customHeader, { paddingTop: insets.top }]}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
          <MaterialIcons name="chevron-left" size={30} color="#212123" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>选择媒体</Text>
        {mode === "multiple" ? (
          <TouchableOpacity onPress={handleConfirm} style={[ styles.confirmButton, selectedItems.length > 0 && styles.confirmButtonActive]}>
            <Text style={[ styles.confirmText, selectedItems.length > 0 && styles.confirmTextActive]}>
              确定{selectedItems.length > 0 ? `(${selectedItems.length})` : ""}
            </Text>
          </TouchableOpacity>
        ) : (
          <View style={styles.placeholder} />
        )}
      </View>
      <MediaGrid
        ref={mediaGridRef}
        selectedItems={selectedItems}
        filterType={filterType === "camera" ? "all" : filterType}
        onItemPress={toggleSelection}
        onCameraPress={handleTakePhoto}
        onFilterChange={setFilterType}
        onSingleSelect={handleSingleSelect}
        onMultipleSelect={handleMultipleSelect}
        mode={mode}
      />
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
  customHeader: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    backgroundColor: "#fff",
    paddingHorizontal: 14,
    borderBottomColor: "#e0e0e0",
  },
  backButton: {
    marginLeft: -8,
  },
  headerTitle: {
    fontSize: 17,
    marginLeft: 40
  },
  confirmButton: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    backgroundColor: "#f0f0f0",
  },
  confirmButtonActive: {
    backgroundColor: "#007AFF",
  },
  confirmText: {
    fontSize: 14,
    color: "#666",
  },
  confirmTextActive: {
    color: "#fff",
  },
  placeholder: {
    width: 60, // 与确定按钮占位相同宽度，保持布局平衡
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  selectedItem: {
    opacity: 0.8,
  },
});
